package com.cube.truthseer.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.cube.truthseer.api.client.AsyncEmailClient;
import com.cube.truthseer.common.entity.dto.EmailInfoDTO;
import com.cube.truthseer.common.exception.BadRequestException;
import com.cube.truthseer.common.utils.CollUtils;
import com.cube.truthseer.common.utils.RandomUtils;
import com.cube.truthseer.common.utils.StringUtil;
import com.cube.truthseer.service.ICodeService;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.cube.truthseer.common.entity.constants.ErrorInfo.Msg.INVALID_VERIFY_CODE;
import static com.cube.truthseer.entity.user.constants.UserConstants.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class CodeServiceImpl implements ICodeService {

    private final StringRedisTemplate stringRedisTemplate;
    private final AsyncEmailClient asyncEmailClient;
    @Override
    //1：是登录，2：注册
    public void sendVerifyCode(String email,int type) {
        String key;
        if(type==1) {
              key = USER_VERIFY_CODE_KEY_LOGIN+email;
        }else   key = USER_VERIFY_CODE_KEY_REGISTER+email;

        //1.查看code是否存在
        String code = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isBlank(code)){
            //2.生成随机验证码
            code = RandomUtils.randomNumbers(4);
            //1：是登录，2：注册
            if(type==1){
                stringRedisTemplate.opsForValue()
                        .set(USER_VERIFY_CODE_KEY_LOGIN + email, code, USER_VERIFY_CODE_TTL);
            }
            else{
                stringRedisTemplate.opsForValue()
                        .set(USER_VERIFY_CODE_KEY_REGISTER + email, code, USER_VERIFY_CODE_TTL);
            }
        }
        //4.发送短信
        log.debug("发送验证码{}",code);
        EmailInfoDTO info = new EmailInfoDTO();
        info.setEmail(email);
        Map<String,String>params = new HashMap<>(1);
        params.put("code",code);
        log.info("code:{}",code);
        info.setTemplateParams(params);
        asyncEmailClient.sendMessage(info);
    }

    @Override
    public void verifyCode(String email, String code,int type) {
        String cacheCode;
        if(type==1){
           cacheCode = stringRedisTemplate.opsForValue().get(USER_VERIFY_CODE_KEY_LOGIN + email);
        }else{
            cacheCode = stringRedisTemplate.opsForValue().get(USER_VERIFY_CODE_KEY_REGISTER + email);
        }

        if(!StringUtil.equals(cacheCode,code)){
            throw new BadRequestException(INVALID_VERIFY_CODE);
        }
    }
}
